package com.ruoyi.fundmonitor.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.attachment.domain.Attachment;
import com.ruoyi.attachment.mapper.AttachmentMapper;
import com.ruoyi.attachment.service.IAttachmentService;
import com.ruoyi.attachment.vo.AttachmentVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fundmonitor.dto.ReleaseFund;
import com.ruoyi.project.infoprojecttarget.domain.InfoProjectTarget;
import com.ruoyi.project.infoprojecttarget.mapper.InfoProjectTargetMapper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.fundmonitor.mapper.InfoFundMonitorMapper;
import com.ruoyi.fundmonitor.domain.InfoFundMonitor;
import com.ruoyi.fundmonitor.service.IInfoFundMonitorService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资金监控Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-13
 */
@Service
public class InfoFundMonitorServiceImpl implements IInfoFundMonitorService 
{
    @Autowired
    private InfoFundMonitorMapper infoFundMonitorMapper;

    @Autowired
    private InfoProjectTargetMapper targetMapper;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private IAttachmentService attachmentService;

    /**
     * 查询资金监控
     * 
     * @param id 资金监控主键
     * @return 资金监控
     */
    @Override
    public InfoFundMonitor selectInfoFundMonitorById(Long id)
    {
        return infoFundMonitorMapper.selectInfoFundMonitorById(id);
    }

    /**
     * 查询资金监控列表
     * 
     * @param infoFundMonitor 资金监控
     * @return 资金监控
     */
    @Override
    public List<InfoFundMonitor> selectInfoFundMonitorList(InfoFundMonitor infoFundMonitor)
    {
        return infoFundMonitorMapper.selectInfoFundMonitorList(infoFundMonitor);
    }

    /**
     * 新增资金监控
     * 
     * @param infoFundMonitor 资金监控
     * @return 结果
     */
    @Override
    public int insertInfoFundMonitor(InfoFundMonitor infoFundMonitor)
    {
        InfoProjectTarget infoProjectTarget = targetMapper.selectInfoProjectTargetById(infoFundMonitor.getProjectTargetId());
        infoFundMonitor.setDepartmentId(infoProjectTarget.getDepartmentId());
        infoFundMonitor.setProjectId(infoProjectTarget.getBaseProjectId());
        infoFundMonitor.setProjectName(infoProjectTarget.getProjectName());
        infoFundMonitor.setPassDownFund(infoProjectTarget.getTotalFunds().toString());
        infoFundMonitor.setImplementationId(infoProjectTarget.getReleaseDepartmentId());
        infoFundMonitor.setFundStatus(1l);
        infoFundMonitor.setCreateTime(DateUtils.getNowDate());
        String start = DateFormatUtils.format(infoFundMonitor.getFundStartTime(), "YYYY-MM-dd");
        String end = DateFormatUtils.format(infoFundMonitor.getFundEndTime(), "YYYY-MM-dd");
        infoFundMonitor.setMonitorDration(start+"-"+end);
        return infoFundMonitorMapper.insertInfoFundMonitor(infoFundMonitor);
    }

    /**
     * 修改资金监控
     * 
     * @param infoFundMonitor 资金监控
     * @return 结果
     */
    @Override
    public int updateInfoFundMonitor(InfoFundMonitor infoFundMonitor)
    {
        //前端传
        //arriveFund  到位资金
        //executeFund 执行资金
        //executeRate 资金执行率  执行资金/下达资金
        return infoFundMonitorMapper.updateInfoFundMonitor(infoFundMonitor);
    }

    /**
     * 批量删除资金监控
     * 
     * @param ids 需要删除的资金监控主键
     * @return 结果
     */
    @Override
    public int deleteInfoFundMonitorByIds(Long[] ids)
    {
        return infoFundMonitorMapper.deleteInfoFundMonitorByIds(ids);
    }

    /**
     * 删除资金监控信息
     * 
     * @param id 资金监控主键
     * @return 结果
     */
    @Override
    public int deleteInfoFundMonitorById(Long id)
    {
        return infoFundMonitorMapper.deleteInfoFundMonitorById(id);
    }

    @Override
    public List<InfoFundMonitor> selectInfoFundMonitorListByTargetId(InfoFundMonitor infoFundMonitor) {
        return infoFundMonitorMapper.selectInfoFundMonitorListByTargetId(infoFundMonitor);
    }

    @Override
    public void updateInfoFundMonitorByStatus(InfoFundMonitor infoFundMonitor) {
        infoFundMonitorMapper.updateInfoFundMonitorByStatus(infoFundMonitor);
    }

    @Override
    public int uploadMuchFiles(Attachment attachment,Integer type) {
        //前端传过来 自己监控id 初始文件名 附件url 备注
        //从url中截取生成的新名字
        String substring = attachment.getAttachmentUrl().substring(attachment.getAttachmentUrl().lastIndexOf("/") + 1);
        attachment.setAttachmentName(substring);
        //设置附件类型
        attachment.setAttachmentType("1");
        attachment.setTableName("info_fund_monitor");
//        if(type.equals(1)){
//
//        }else{
//            Attachment att=new Attachment();
//            att.setInfoDetailId(attachment.getInfoDetailId());
//            att.setInfoId(attachment.getInfoId());
//            List<Attachment> attachments=attachmentMapper.selectAttachmentList(att);
//            if(attachments.size()>0){
//                Attachment attach= attachments.get(0);
//                //删除服务器附件
//                attachmentService.deleteServerFile(attach.getAttachmentUrl());
//                //删除数据库附件
//                attachmentMapper.deleteAttachmentByAttachmentId(attach.getAttachmentId());
//            }
//            attachment.setTableName("info_beforehand_evaluate_detail");
//        }
        //设置创建人
        attachment.setCreateUser(SecurityUtils.getUserId());
        //创建时间
        attachment.setCreateTime(new Date());
        return attachmentMapper.insertAttachment(attachment);
    }

    @Override
    public int batchInsert(AttachmentVo attachmentVo) {
        try {
            Long infoId = attachmentVo.getInfoId();
            List<Attachment> attachments = attachmentVo.getAttachments();
            Attachment attachment1 = new Attachment();
            attachment1.setInfoId(infoId.toString());
            attachment1.setTableName("info_fund_monitor");
            attachment1.setAttachmentType("1");
            List<Attachment> attachments2 = attachmentMapper.selectAttachmentList(attachment1);
            for (Attachment attachment : attachments) {
                String substring = attachment.getAttachmentUrl().substring(attachment.getAttachmentUrl().lastIndexOf("/") + 1);
                attachment.setAttachmentName(substring);
            }
            List<String> collect2 = attachments.stream().map(Attachment::getAttachmentName).collect(Collectors.toList());
            List<Attachment> collect1 = attachments2.stream().filter(x ->!collect2.contains(x.getAttachmentName())).collect(Collectors.toList());
            //删除
            if (collect1.size() > 0){
                for (Attachment attachment : attachments2) {
                    //有点问题前端需要给我传分解后的名称
                    //attachmentService.deleteServerFile(attachment.getAttachmentUrl());
                    attachmentService.deleteAttachmentByAttachmentName(attachment.getAttachmentName());
                }
            }
            //添加
            if (attachments.size() != 0){
                for (Attachment attachment : attachments) {
                    List<Attachment> attachments1 = attachmentMapper.selectAttachmentList(attachment);
                    if (attachments1.size() != 0){
                       continue;
                    }
                    String substring = attachment.getAttachmentUrl().substring(attachment.getAttachmentUrl().lastIndexOf("/") + 1);
                    attachment.setAttachmentName(substring);
                    attachment.setAttachmentType("1");
//                attachment.setInfoId(infoId.toString());
                    attachment.setTableName("info_fund_monitor");
                    attachmentService.insertAttachment(attachment);
                }
                return 1;
            }
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult releaseFundMultiple(ReleaseFund releaseFund) {
        String ids = releaseFund.getIds();
        String[] split = ids.split(",");

        //数量达到四条不能下达，如果有当前监控期间不可下达
        InfoFundMonitor infoFundMonitor = new InfoFundMonitor();
        for (String id : split) {
            //判断是否超过可监控数量
            infoFundMonitor.setProjectTargetId(Long.valueOf(id));
            List<InfoFundMonitor> monitors = infoFundMonitorMapper.selectInfoFundMonitorListByTargetId(infoFundMonitor);
            if (monitors.size() >= 4){
                return AjaxResult.error("请查看是否满足批量下达条件！");
            }
            //判断当前监控周期是否存在监控
            infoFundMonitor.setFundStartTime(releaseFund.getFundStartTime());
            infoFundMonitor.setFundEndTime(releaseFund.getFundEndTime());
            List<InfoFundMonitor> monitors1 = infoFundMonitorMapper.selectInfoFundMonitorListByTargetId(infoFundMonitor);
            if (monitors1.size() >= 1){
                return AjaxResult.error("请查看是否满足批量下达条件！");
            }
            infoFundMonitor.setProjectTargetId(Long.valueOf(id));
            infoFundMonitor.setFundStartTime(releaseFund.getFundStartTime());
            infoFundMonitor.setFundEndTime(releaseFund.getFundEndTime());
            insertInfoFundMonitor(infoFundMonitor);
        }
        return AjaxResult.success("下达成功！");
    }
}
